package com.dianzi.certification.service.impl;

import com.dianzi.certification.constants.ResponseConstant;
import com.dianzi.certification.entity.CustomUserDetail;
import com.dianzi.certification.entity.Role;
import com.dianzi.certification.entity.User;
import com.dianzi.certification.entity.UserRole;
import com.dianzi.certification.service.AuthService;
import com.dianzi.certification.service.RoleService;
import com.dianzi.certification.service.UserRoleService;
import com.dianzi.certification.vo.R;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author copa
 * @createDate 2022-03-07 23:20
 * @function
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private AuthService authService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        R<User> userRes = authService.findByName(username);
        if (userRes.getCode() == ResponseConstant.STATUS_FAIL) {
            // 不存在该用户
            throw new UsernameNotFoundException("该用户不存在！");
        }

        R<UserRole> userRoleRes = userRoleService.findByUserId(userRes.getData().getId());

        if (userRoleRes.getCode() == ResponseConstant.STATUS_FAIL) {
            // 没有管理员权限
            throw new UsernameNotFoundException("该用户权限不足！");
        }
        // 登录成功
        List<GrantedAuthority> authorities = new ArrayList<>();

        User user = userRes.getData();

        Role role = roleService.findById(userRoleRes.getData().getRoleId());
        authorities.add(new SimpleGrantedAuthority(role.getName()));

        CustomUserDetail customerUser = CustomUserDetail.builder()
                .user(user)
                // 将该权限添加到security
                .authorities(authorities)
                .build();

        return customerUser;
    }
}
